// electron/main.js
const { app, BrowserWindow, session, ipcMain, dialog } = require('electron');
const path = require('path');
const { autoUpdater } = require('electron-updater');

let mainWindow = null;

function openChildWindow(url, jsCode) {
  const child = new BrowserWindow({
    width: 10,
    height: 10,
    autoHideMenuBar: true,
    show: false, // 创建时隐藏窗口
    icon: path.join(__dirname, 'baoyilogo.ico'),
    webPreferences: {
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload/childPreload.js'),
    },
  });
  child.loadURL(url);

  // 页面加载完成后执行代码
  child.webContents.on('did-finish-load', () => {
    child.webContents.executeJavaScript(jsCode);
  });

  child.on('ready-to-show', () => {
    child.minimize(); // 窗口最小化
  });
  return child;
}

async function createWindow() {
  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;

  // 加载插件扩展
  const extensionPath = app.isPackaged
    ? path.join(process.resourcesPath, 'baoyi_collection_plugin')
    : path.join(__dirname, 'baoyi_collection_plugin');

  await session.defaultSession.clearStorageData({
    storages: ['serviceworkers'],
  });

  try {
    const ext = await session.defaultSession.loadExtension(extensionPath, {
      allowServiceWorkers: true, // 强制启用 Service Worker
      allowFileAccess: true, // 若扩展有 file: 资源访问，务必加上
    });
    console.log('[main] 插件加载成功:', ext.name);
  } catch (err) {
    console.error('[main] 插件加载失败:', err);
  }

  // 创建主窗口
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    icon: path.join(__dirname, 'baoyilogo.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload/preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  });

  // 加载 URL
  if (isDev) {
    await mainWindow.loadURL('http://localhost:5201');
  } else {
    await mainWindow.loadURL('https://java.baoyierp.com');
  }
  // 可选：打开 devtools
  if (isDev) {
    mainWindow.webContents.openDevTools();
  }

  autoUpdater.checkForUpdatesAndNotify();
  autoUpdater.on('update-available', function (info) {
    mainWindow.webContents.send('update-available', info);
  });
  autoUpdater.on('update-not-available', function (info) {
    mainWindow.webContents.send('update-not-available', info);
  });
  autoUpdater.on('download-progress', (progress) => {
    mainWindow.webContents.send('download-progress', progress.percent);
  });
  autoUpdater.on('update-downloaded', function () {
    mainWindow.webContents.send('update-downloaded');
    dialog
      .showMessageBox({
        type: 'info',
        buttons: ['立即更新', '以后再说'],
        title: 'Baoyi ERP 更新程序',
        message: '已下载新版本。关闭并安装应用程序以更新。',
      })
      .then((response) => {
        if (response.response === 0) {
          autoUpdater.quitAndInstall();
        }
      });
  });
}

ipcMain.on('from-content-finish-task', (event, data) => {
  mainWindow.webContents.send('from-child-web-content-finish-task', data);
});
ipcMain.on('start-auto-collect', (event, data) => {
  const { url, collectPage, taskId } = data;
  const jsCode = `
    window.postMessage({
      type: "BAOYI_ERP_MESSAGE",
      action: "startTask",
      data: {
        collectPage: ${collectPage},
        taskId: ${taskId},
      },
    });
  `;
  openChildWindow(url, jsCode);
});

app.whenReady().then(createWindow);

// 关闭行为
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
